package org.nmgyjt.springboot.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.nimbusds.jose.JOSEException;
import org.apache.commons.lang.StringUtils;
import org.nmgyjt.springboot.beans.admin.CsSystemBeyongDeptSelectBean;
import org.nmgyjt.springboot.beans.admin.CsSystemIDSelectBean;
import org.nmgyjt.springboot.beans.admin.CsSystemSourceLevelBean;
import org.nmgyjt.springboot.beans.admin.StatisticBean;
import org.nmgyjt.springboot.beans.vo.PageVo;
import org.nmgyjt.springboot.entity.ApiRes;
import org.nmgyjt.springboot.entity.admin.CsSystemAdmin;
import org.nmgyjt.springboot.entity.admin.CsSystemDeptResponse;
import org.nmgyjt.springboot.entity.admin.IDAASOrgEntity;
import org.nmgyjt.springboot.entity.admin.IdaasArea;
import org.nmgyjt.springboot.entity.equipage.Equipage;
import org.nmgyjt.springboot.entity.rescueTeam.RescueTeam;
import org.nmgyjt.springboot.entity.sms.YuFuMSSendEntity;
import org.nmgyjt.springboot.mapper.CsSystemAdminMapper;
import org.nmgyjt.springboot.mapper.EquipageMapper;
import org.nmgyjt.springboot.mapper.RescueTeamMapper;
import org.nmgyjt.springboot.service.*;
import org.nmgyjt.springboot.utils.ZWWXUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.text.ParseException;
import java.util.*;

@Service
public class RescueTeamServiceImpl extends ServiceImpl<RescueTeamMapper, RescueTeam> implements RescueTeamService {
    @Autowired
    private RescueTeamMapper rescueTeamMapper;

    @Autowired
    private EquipageMapper equipageMapper;

    @Autowired
    private EquipageService equipageService;

    @Autowired
    private ICsSystemDeptService iCsSystemDeptService;

    @Autowired
    private IIdaasAreaService iIdaasAreaService;

    @Autowired
    SendSMSServiceImpl smsService;

    @Autowired
    CsSystemAdminMapper csSystemAdminMapper;
    @Autowired
    ZWWXUtils zwwxUtils;

    @Override
    public RescueTeam getByDepId(String depId, Page<Equipage> page, String equipageName) {
        QueryWrapper<RescueTeam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dep_id", depId);
        queryWrapper.ne("state", "1");
        RescueTeam rescueTeam = null;
        try {
            rescueTeam = rescueTeamMapper.selectOne(queryWrapper);
            if (!ObjectUtils.isEmpty(rescueTeam)) {
//                rescueTeam.setTeamNum(idaasService.findUsersByDepId(depId).size());
                QueryWrapper<Equipage> equipageQueryWrapper = new QueryWrapper<>();
                equipageQueryWrapper.eq("rescue_team_id", rescueTeam.getId());
                equipageQueryWrapper.ne("state", "1");
                if (!ObjectUtils.isEmpty(equipageName)) {
                    equipageQueryWrapper.like("equipage_name", "%" + equipageName + "%");
                }
                Page<Equipage> equipageList = equipageMapper.selectPage(page, equipageQueryWrapper);
                PageVo<Equipage> pageVo = new PageVo();
                pageVo.setTotal(equipageList.getTotal());
                pageVo.setList(equipageList.getRecords());
                rescueTeam.setPageData(pageVo);
            }
//            else {
//                RescueTeam rescueTeam1 = new RescueTeam();
//                CsSystemIDSelectBean csSystemIDSelectBean = new CsSystemIDSelectBean();
//                csSystemIDSelectBean.setId(depId);
//                CsSystemDeptResponse detailCsSystemOrg = iCsSystemDeptService.detailCsSystemOrg(csSystemIDSelectBean);
//                if (!ObjectUtils.isEmpty(detailCsSystemOrg)) {
//                    rescueTeam1.setTeamName(detailCsSystemOrg.getName());
//                    String leveled = "";
//                    String snycLevel = "";
//                    String levelCityRegionCode = "";
//                    String levelCountyRegionCode = "";
//                    rescueTeam1.setTeamType(detailCsSystemOrg.getSourceType());
//                    CsSystemSourceLevelBean csSystemSourceLevelBean = detailCsSystemOrg.getSourceLevel();
//                    if (!ObjectUtils.isEmpty(csSystemSourceLevelBean) &&
//                            !ObjectUtils.isEmpty(csSystemSourceLevelBean.getCountry())) {
//                        leveled = leveled + "国家级,";
//                        snycLevel = snycLevel + "1,";
//                    }
//                    if (!ObjectUtils.isEmpty(csSystemSourceLevelBean) &&
//                            !ObjectUtils.isEmpty(csSystemSourceLevelBean.getProvince())) {
//                        leveled = leveled + "自治区级,";
//                        snycLevel = snycLevel + "2,";
//                    }
//                    if (!ObjectUtils.isEmpty(csSystemSourceLevelBean) &&
//                            !ObjectUtils.isEmpty(csSystemSourceLevelBean.getCity())) {
//                        QueryWrapper<IdaasArea> idaasAreaQueryWrapper = new QueryWrapper<>();
//                        IdaasArea area = iIdaasAreaService.getById(csSystemSourceLevelBean.getCity());
//                        leveled = leveled + area.getName() + "级，";
//                        snycLevel = snycLevel + "3,";
//                        levelCityRegionCode = area.getCode();
//                    }
//                    if (!ObjectUtils.isEmpty(csSystemSourceLevelBean) &&
//                            !ObjectUtils.isEmpty(csSystemSourceLevelBean.getCounty())) {
//                        IdaasArea area = iIdaasAreaService.getById(csSystemSourceLevelBean.getCounty());
//                        leveled = leveled + area.getName() + "级，";
//                        snycLevel = snycLevel + "4,";
//                        levelCountyRegionCode = area.getCode();
//                    }
//                    if (!"".equals(leveled)) {
//                        leveled = leveled.substring(0, leveled.length() - 1);
//                        snycLevel = snycLevel.substring(0, snycLevel.length() - 1);
//                    }
//                    rescueTeam1.setLeveled(leveled);
//                    rescueTeam1.setSyncLevel(snycLevel);
//                    rescueTeam1.setLevelCityRegionCode(levelCityRegionCode);
//                    rescueTeam1.setLevelCountyRegionCode(levelCountyRegionCode);
//                }
//                CsSystemBeyongDeptSelectBean csSystemBeyongDeptSelectBean = new CsSystemBeyongDeptSelectBean();
//                csSystemBeyongDeptSelectBean.setId(depId);
//                csSystemBeyongDeptSelectBean.setType("救援队伍");
////                IDAASOrgEntity idaasOrgEntity=iCsSystemDeptService.detailCsSystemBeyongOrg(csSystemBeyongDeptSelectBean);
////                rescueTeam1.setDepartment(idaasOrgEntity.getName());
////                rescueTeam1.setDepartmentId(idaasOrgEntity.getId());
////                rescueTeam1.setTeamNum(idaasService.findUsersByDepId(depId).size());
//                return rescueTeam1;
//            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return rescueTeam;
    }

    @Override
    public Boolean deleteByDepId(String depId) {
        QueryWrapper<RescueTeam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dep_id", depId);
        queryWrapper.ne("state", "1");
        RescueTeam rescueTeam = rescueTeamMapper.selectOne(queryWrapper);
        if (!ObjectUtils.isEmpty(rescueTeam)) {
            int num = rescueTeamMapper.deleteByDepId(rescueTeam.getDepId());
            if (num > 0) {
                equipageMapper.deleteByteamId(rescueTeam.getId());
                return true;
            } else {
                return false;
            }
        }
        return true;
    }

    @Override
    public PageVo<Equipage> getRescueTeamInfo(String id, Page<Equipage> page) {
        QueryWrapper<Equipage> equipageQueryWrapper = new QueryWrapper<>();
        equipageQueryWrapper.eq("rescue_team_id", id);
        Page<Equipage> equipageList = equipageMapper.selectPage(page, equipageQueryWrapper);
        PageVo<Equipage> pageVo = new PageVo();
        pageVo.setTotal(equipageList.getTotal());
        pageVo.setList(equipageList.getRecords());
        return pageVo;
    }

    public RescueTeam findById(Long id) {
        RescueTeam rescueTeam = rescueTeamMapper.selectById(id);
        if (!ObjectUtils.isEmpty(rescueTeam)) {
            QueryWrapper<Equipage> equipageQueryWrapper = new QueryWrapper<>();
            equipageQueryWrapper.eq("rescue_team_id", rescueTeam.getId());
            List<Equipage> equipageList = equipageMapper.selectList(equipageQueryWrapper);
            rescueTeam.setEquipageList(equipageList);
        }
        return rescueTeam;
    }

    @Override
    public ApiRes insertOrUpdate(RescueTeam rescueTeam) {
        try {
            boolean b = false;
            if (!ObjectUtils.isEmpty(rescueTeam.getId())) {
                RescueTeam rescueTeam1 = this.getById(rescueTeam.getId());
                if (ObjectUtils.isEmpty(rescueTeam1.getHeadPhone())) {
                    b = true;
                } else {
                    if (!rescueTeam1.getHeadPhone().equals(rescueTeam.getHeadPhone())) {
//                        String ssoAccessToken = zwwxUtils.getGovWxToken();
//                        Integer code = zwwxUtils.getZWUserInfo(rescueTeam1.getHeadPhone(), null, ssoAccessToken);
                        b = true;
                    }
                }
            }
            List<Equipage> equipageList = rescueTeam.getEquipageList();
            rescueTeam.setHeadPhone(rescueTeam.getHeadPhone().trim());
            rescueTeam.setState("0");
//            rescueTeam.setHeadId(rescueTeam.getHeadPhone());
            this.saveOrUpdate(rescueTeam);

            if (!ObjectUtils.isEmpty(rescueTeam.getId()) && !ObjectUtils.isEmpty(equipageList) && equipageList.size() > 0) {
                for (Equipage equipage : equipageList) {
                    equipage.setRescueTeamId(rescueTeam.getId());
                    if ("防汛抢险".equals(equipage.getEquipageType())) {
                        equipage.setEquipageTypeCode("ZB000017");
                    }
                    if ("交通运输".equals(equipage.getEquipageType())) {
                        equipage.setEquipageTypeCode("ZB000018");
                    }
                    if ("工程救援".equals(equipage.getEquipageType())) {
                        equipage.setEquipageTypeCode("ZB000019");
                    }
                    if ("环境监测".equals(equipage.getEquipageType())) {
                        equipage.setEquipageTypeCode("ZB000020");
                    }
                    if ("电力抢修".equals(equipage.getEquipageType())) {
                        equipage.setEquipageTypeCode("ZB000021");
                    }
                    if ("预警预测".equals(equipage.getEquipageType())) {
                        equipage.setEquipageTypeCode("ZB000013");
                    }
                    if ("个体防护".equals(equipage.getEquipageType())) {
                        equipage.setEquipageTypeCode("ZB000014");
                    }
                    if ("通信信息".equals(equipage.getEquipageType())) {
                        equipage.setEquipageTypeCode("ZB000015");
                    }
                    if ("灭火抢险".equals(equipage.getEquipageType())) {
                        equipage.setEquipageTypeCode("ZB000016");
                    }

                    equipage.setState("0");
                }
            }
            //删除前端未传输的装备id数据
            if (!ObjectUtils.isEmpty(rescueTeam.getIds())) {
                String[] ids = rescueTeam.getIds().split(",");
                equipageMapper.deleteByIds(ids);
            }
            equipageService.saveOrUpdateBatch(equipageList);
            QueryWrapper<Equipage> equipageQueryWrapperCount = new QueryWrapper<>();
            equipageQueryWrapperCount.eq("rescue_team_id", rescueTeam.getId());
            equipageQueryWrapperCount.ne("state", "1");
            rescueTeam.setEquipageNum(equipageService.count(equipageQueryWrapperCount));
            Boolean s = this.saveOrUpdate(rescueTeam);

            //发送通知短信
            if (b && s) {
                String ssoAccessToken = zwwxUtils.getGovWxToken();
                Integer code = zwwxUtils.getZWUserInfo(rescueTeam.getHeadPhone(), "rescue/rescue-detail?depId=" + rescueTeam.getDepId(), ssoAccessToken);
                rescueTeam.setSnycState(code.toString());
                this.saveOrUpdate(rescueTeam);
                YuFuMSSendEntity sendEntity = new YuFuMSSendEntity();
                List<String> params = new ArrayList<>();
                List<String> phone = new ArrayList<>();
                phone.add("+86" + rescueTeam.getHeadPhone());
                params.add(rescueTeam.getHeadName());
                params.add("救援队伍" + rescueTeam.getTeamName());
                sendEntity.setTemplateParamSet(params);
                sendEntity.setPhoneNumSet(phone);
                sendEntity.setType("notification");
                smsService.sendMS(sendEntity);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ApiRes.customFail("保存失败！");
        }

        return ApiRes.ok(rescueTeam.getId());
    }

    @Override
    public Map<String, Object> statisticRescueTeam(StatisticBean statisticBean) {
        QueryWrapper<CsSystemAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", statisticBean.getCreatedBy()).orderByDesc("id").last("limit 1" );
        CsSystemAdmin csSystemAdmin = csSystemAdminMapper.selectOne(queryWrapper);
        Map<String, Object> retMap = new LinkedHashMap<>();
        if(ObjectUtils.isEmpty(csSystemAdmin)){
            return retMap;
        }
        String sql = " AND r.state <> '1'";
        if (StringUtils.isNotEmpty(statisticBean.getCreatedBy())) {
            sql = sql + " AND a.superior_org='" + csSystemAdmin.getOrgId() + "'";
        } else {
            sql = sql + " AND a.superior_org='-1'";
        }
        if (StringUtils.isNotEmpty(statisticBean.getName())) {
            sql = sql + " AND a.org_name like '%" + statisticBean.getName() + "%'";
        }
        if (StringUtils.isNotEmpty(statisticBean.getType())) {
            JSONArray jsonArray = JSON.parseArray(statisticBean.getType());
            String type = jsonArray.getString(jsonArray.size() - 1);
            sql = sql + " AND ext.source_type like '%" + type + "%'";
        }
        if (StringUtils.isNotEmpty(statisticBean.getOrgId())) {
            sql = sql + " OR ext.source_level like '%" + statisticBean.getOrgId() + "%'";
        }

        String sql2 = "";
        if (StringUtils.isNotEmpty(statisticBean.getStatus())) {
            if ("1".equals(statisticBean.getStatus())) {
                sql2 = sql2 + " AND a.state = '0' ";
            }
            if ("2".equals(statisticBean.getStatus())) {
                sql2 = sql2 + " AND a.state = '2' ";
            }

        }
        List<Map<String, Object>> List = rescueTeamMapper.statisticRescueTeam(sql, sql2);
        List<Map<String, Object>> maplist = rescueTeamMapper.statisticRescueTeamInfoCount(csSystemAdmin.getOrgId(), "%" + statisticBean.getOrgId() + "%");
        int doneCount=rescueTeamMapper.statisticRescueTeamCountDoneStatus(csSystemAdmin.getOrgId(), "%" + statisticBean.getOrgId() + "%");
        int unDoneCount=maplist.size()-doneCount;
        Integer peopleNum = 0;
        Integer equipageNum = 0;
        for (Map<String, Object> map : maplist) {
            peopleNum += Integer.valueOf(String.valueOf(map.get("team_num") == null ? 0 : map.get("team_num")));
            equipageNum += Integer.valueOf(String.valueOf(map.get("equipage_num") == null ? 0 : map.get("equipage_num")));

        }
        Integer rescueTeamTypeCount = rescueTeamMapper.statisticRescueTeamCount(csSystemAdmin.getOrgId(), "%" + statisticBean.getOrgId() + "%");
        Integer rescueTeamCount = maplist.size();

        retMap.put("rescueTeamTypeCount", rescueTeamTypeCount);
        retMap.put("rescueTeamCount", rescueTeamCount);
        retMap.put("peopleNum", peopleNum);
        retMap.put("equipageNum", equipageNum);
        retMap.put("doneCount", doneCount);
        retMap.put("unDoneCount", unDoneCount);
        retMap.put("list", List);
        return retMap;
    }

    @Override
    public ApiRes testSendSms() {
        YuFuMSSendEntity sendEntity = new YuFuMSSendEntity();
        List<String> params = new ArrayList<>();
        List<String> phone = new ArrayList<>();
        phone.add("+8618519275273");
        params.add("杜成龙");
        params.add("救援队伍");
        sendEntity.setTemplateParamSet(params);
        sendEntity.setPhoneNumSet(phone);
        sendEntity.setType("notification");
        String s = smsService.sendMS(sendEntity);
        return ApiRes.ok(s);
    }

    @Override
    public void snycZwwxByHeadPhone() {
        QueryWrapper<RescueTeam> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNotNull("head_phone");
        queryWrapper.ne("snyc_state", "0");
        List<RescueTeam> rescueTeamList = rescueTeamMapper.selectList(queryWrapper);
        for (RescueTeam rescueTeam : rescueTeamList) {
            String ssoAccessToken = zwwxUtils.getGovWxToken();
            Integer code = zwwxUtils.getZWUserInfo(rescueTeam.getHeadPhone(), "rescue/rescue-detail?depId=" + rescueTeam.getDepId(), ssoAccessToken);
            rescueTeam.setSnycState(code.toString());
            this.saveOrUpdate(rescueTeam);
        }
    }

    public static void main(String[] args) {
        String s = "[\"jiose4\",\"jiose4\",\"ROLE_ADMIN\",\"ROLE_ADMIN\",\"ROLE_ADMIN\",\"ROLE_ADMIN\",\"ROLE_ADMIN\",\"ROLE_ADMIN\"]";
        String y = "ROLE_ADMIN";
        System.out.println(s.indexOf(y));
    }


}
